import React, { useEffect, useRef, useState } from 'react';

import { Avatar, Space, Progress } from 'antd';
import {
  MinusOutlined,
  CloseOutlined,
  BorderOutlined,
} from '@ant-design/icons';
import { registerBridge, sendMessage } from './message';
import SelectPath from './components/selectPath';
import CloseApp from './components/closeApp';
import UpdateCheck from './components/updateCheck';
import QuitTask from './components/quitTask';

export default function Home() {
  const iframeRef = useRef(null);
  const { mid, coName, coLogo } = window.electron.store.get('user');
  const baseUrl = window.electron.store.get('baseUrl');
  const iframeUrl = `${baseUrl}electron?common=true`;

  const [folderPath, setFolderPath] = useState<string>('');
  const [pathVisible, setPathVisible] = useState<boolean>(false);
  const [closeVisible, setCloseVisible] = useState<boolean>(false);
  const [updateVisible, setUpdateVisible] = useState<boolean>(false);
  const [quitVisible, setQuitVisible] = useState<boolean>(false);
  const [quitData, setQuitData] = useState<any>({});

  const [percent, setPercent] = useState<number>(0);
  const [showPercent, setShowPercent] = useState<boolean>(false);

  window.electron.ipcRenderer.on('give-folder-path', (path: string) => {
    if (!path) {
      setPathVisible(true);
    } else {
      setFolderPath(path);
    }
  });

  window.electron.ipcRenderer.on('get-histroy-list', (data) => {
    sendMessage.setHistroyList(iframeRef, data);
  });

  //  关闭设置弹窗
  window.electron.ipcRenderer.on('save-folder-path', (path: string) => {
    console.log('修改path', path);

    setFolderPath(path);
  });

  window.electron.ipcRenderer.on('downsuccess', (payload: any) => {
    changeStatus();
  });

  window.electron.ipcRenderer.on('uploadloading', (data: any) => {
    setTimeout(() => {
      sendMessage.setUpLoading(iframeRef, data);
    }, 10);
  });

  // 关闭
  window.electron.ipcRenderer.on('win-close-tips', () => {
    setCloseVisible(true);
    console.log('关闭弹窗');
  });

  window.electron.ipcRenderer.on('win-quiit-tips', (data) => {
    setQuitVisible(true);
    setQuitData(data);
    console.log('关闭弹窗');
  });

  // 打开检查更新弹窗
  window.electron.ipcRenderer.on('update-check', () => {
    setUpdateVisible(true);
  });

  // 打开检查更新弹窗
  window.electron.ipcRenderer.on('downloadProgress', (data) => {
    setPercent(Math.round(data.percent));
  });
  window.electron.ipcRenderer.on('downloadEnd', (data) => {
    setShowPercent(!data);
  });

  const logout = () => {
    window.electron.store.set('user', {});
    window.electron.ipcRenderer.sendMessage('login:openwindow');
    window.electron.ipcRenderer.sendMessage('index:closewindow');
  };

  const changeStatus = () => {
    const downProject = window.electron.store.get('downProject') ?? {};
    const projects = Object.keys(downProject).map((td) => {
      return {
        name: td,
        ...downProject[td],
      };
    });
    sendMessage.setFolderStatus(iframeRef, {
      pcMainId: window.electron.store.get('mainId'),
      projects,
    });
  };

  const doOperton = (type) => {
    window.electron.ipcRenderer.sendMessage('index:opertion', type);
  };

  useEffect(() => {
    // 监听来自 iframe 页面的消息
    window.electron.ipcRenderer.sendMessage('get-folder-path'); // 初次进入获取path
    window.removeEventListener('message', () => {});

    registerBridge((data: any, key: string) => {
      switch (key) {
        case 'login':
          window.electron.store.set('user', { ...data });
          break;
        case 'renderFinish':
          window.electron.ipcRenderer.sendMessage('get-histroy'); // 初次进入获取path
          changeStatus();
          break;

        case 'getFolderStatus':
          // window.electron.ipcRenderer.sendMessage('get-histroy');
          changeStatus();
          break;
        case 'synchronous':
          // 同步，下载
          const downProject = window.electron.store.get('downProject') ?? {};
          downProject[data.projectName] = {
            busId: data.busId,
            pjId: data.pjId,
          };
          window.electron.store.set('downProject', downProject);
          window.electron.ipcRenderer.sendMessage('file:download', data);
          break;
        case 'logout':
          logout();
          break;
        case 'openBrowser':
          console.log('打开网页');
          window.electron.ipcRenderer.sendMessage('openExternal', data.url);
          break;
        case 'setPath':
          window.electron.ipcRenderer.sendMessage('get-folder-path');
          setPathVisible(true);
          break;
        case 'openFolder':
          window.electron.ipcRenderer.sendMessage('openFolder', data.path);
          break;
        case 'upload':
          window.electron.ipcRenderer.sendMessage('file:upload');
          break;
        default:
          break;
      }
    });

    return () => {
      window.removeEventListener('message', () => {});
    };
  }, []);

  return (
    <div>
      <div
        style={{
          textAlign: 'center',
          background: '#f5f5f5',
          height: 37,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <div
          style={{
            width: 'calc(100vw - 182px)',
            '-webkit-app-region': 'drag',
          }}
        >
          <Avatar
            style={{ marginRight: '0.8rem' }}
            shape="square"
            size={34}
            src={coLogo}
          />
          {coName}
        </div>
        <div
          style={{
            position: 'absolute',
            right: 10,
            fontSize: 12,
            top: 10,
            background: '#f5f5f5',
          }}
        >
          <Space size={20}>
            <MinusOutlined
              onClick={(e) => {
                e.preventDefault();
                doOperton('hide');
              }}
              style={{ cursor: 'pointer' }}
            />

            <BorderOutlined
              style={{ cursor: 'pointer' }}
              onClick={(e) => {
                e.preventDefault();

                doOperton('full');
              }}
            />
            <CloseOutlined
              style={{ cursor: 'pointer' }}
              onClick={(e) => {
                e.preventDefault();
                doOperton('close');
              }}
            />
          </Space>
        </div>
      </div>
      <div>
        <div style={{ height: 'calc(100vh - 29px)' }}>
          <iframe
            title="文档"
            width="100%"
            height="100%"
            frameBorder="0"
            style={{ border: 'none' }}
            ref={iframeRef}
            src={`${iframeUrl}&mid=${mid}`}
          />
        </div>
      </div>

      <UpdateCheck
        showPercent={showPercent}
        percent={percent}
        visible={updateVisible}
        setVisible={(reload: boolean) => {
          if (reload) {
            // window.electron.ipcRenderer.sendMessage('path:save', folderPath);
          }
          setUpdateVisible(false);
        }}
      />
      {pathVisible && (
        <SelectPath
          path={folderPath}
          visible={pathVisible}
          setVisible={(reload: boolean) => {
            if (reload) {
              window.electron.ipcRenderer.sendMessage('path:save', folderPath);
            }
            setPathVisible(false);
          }}
        />
      )}

      <CloseApp
        visible={closeVisible}
        setVisible={(reload: boolean) => {
          if (reload) {
            // window.electron.ipcRenderer.sendMessage('path:save', folderPath);
          }
          setCloseVisible(false);
        }}
      />

      <QuitTask
        quitData={quitData}
        visible={quitVisible}
        setVisible={(reload: boolean) => {
          if (reload) {
            // window.electron.ipcRenderer.sendMessage('path:save', folderPath);
          }
          setQuitVisible(false);
        }}
      />
    </div>
  );
}
